package com.putao.album.tag;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.dialog.DialogBuilderFactory;
import com.putao.album.dialog.ImportDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.tag.adapter.TagAblumAdapter;
import com.putao.album.tag.bean.TagAlbumItem;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.widget.pullrefresh.PullToRefreshBase;
import com.putao.album.widget.pullrefresh.PullToRefreshGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/28.
 * <p/>
 * 标签相册页面
 */
public class ActivityTagAlbum extends BaseActivity {
    private TextView title_tv;
    private Button right_btn;
    private PullToRefreshGridView gv_album;
    private View list_empty_view;
    private TagAblumAdapter mTagAblumAdapter;
    private List<TagAlbumItem> mDatalist = new ArrayList<TagAlbumItem>();
    private String nextPage = "1";
    private boolean mIsLastPage = false;
    private boolean mIsRefreshing = false;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_tag_album;
    }

    @Override
    public void doInitSubViews(View view) {
        setPageTitle();
        queryViewById(R.id.back_btn, true);
        gv_album = queryViewById(R.id.gv_album);
        list_empty_view = queryViewById(R.id.list_empty_view);
        gv_album.setOnItemClickListener(onItemClickListener);
        gv_album.getRefreshableView().setOnItemClickListener(onItemClickListener);
        gv_album.getRefreshableView().setNumColumns(2);
        gv_album.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                refreshData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
//                doGetData();

            }
        });

        gv_album.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                Loger.d("lastitemvisible");
                doGetData();
            }
        });
        gv_album.getRefreshableView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (gv_album.getRefreshableView().getChildAt(0) != null && mTagAblumAdapter.getItemWidth() == 0) {
                    int width = gv_album.getRefreshableView().getChildAt(0).getWidth();
                    mTagAblumAdapter.setItemWidth(width);
                    mTagAblumAdapter.notifyDataSetChanged();
                }
            }
        });

        list_empty_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImportDialog();
            }
        });
        EventBus.getDefault().register(this);
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TagAlbumItem item = mDatalist.get(position);
            if (item.Type == TagAlbumItem.DataType.NORMAL) {
                Bundle bundle = new Bundle();
                //TODO:传入标签的名称
                bundle.putString("tag_name", mDatalist.get(position).album_name);
                bundle.putString("tag_id", mDatalist.get(position).tag_id);
                ActivityHelper.startActivity(mActivity, (Integer.valueOf(item.count) > 0) ? ActivityTagAlbumPhotoList.class : ActivityTagAlbumPhotoAdd.class, bundle);
            } else {
                showImportDialog();
            }
        }
    };

    void showImportDialog() {
        new DialogBuilderFactory<ImportDialogBuilder>(mContext, DialogBuilderFactory.DialogType.IMPORT)
                .Builder()
                .setDialogButtonOnClickListener(mAddTagDialogListener)
                .setMessage("添加新标签")
                .setNegativeButton(R.string.btn_ok)
                .setPositiveButton(R.string.btn_cancle).Create().show();
    }

    ImportDialogBuilder.DialogButtonOnClickListener mAddTagDialogListener = new ImportDialogBuilder.DialogButtonOnClickListener() {
        @Override
        public void positiveOnClick(Dialog dialog, String importText) {
            dialog.dismiss();
        }

        @Override
        public void negativeOnClick(Dialog dialog, String importText) {
            dialog.dismiss();
            if (!StringHelper.isEmpty(importText)) {
                doAddTag(importText);
            }
        }
    };

    /**
     * 添加用户标签
     *
     * @param tagText
     */
    void doAddTag(final String tagText) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("tag", tagText);
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_ADD_USER_TAG, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("tag_name", tagText);

                        ActivityHelper.startActivity(mActivity, ActivityTagAlbumPhotoAdd.class, bundle);
                        TagAlbumItem item = new TagAlbumItem();
                        item.album_name = tagText;
                        item.count = "0";
                        //item.cover_url = photo;
                        //item.tag_id = tag_id;
                        item.Type = TagAlbumItem.DataType.NORMAL;
                        mDatalist.add(mDatalist.size() - 1, item);
                        mTagAblumAdapter.notifyDataSetChanged();
                        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_DELETE_OR_ADD_TAG_SUCCESS));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    void setPageTitle() {
        title_tv = queryViewById(R.id.title_tv);
        title_tv.setText(R.string.page_title_tag_album);
        right_btn = queryViewById(R.id.right_btn, true);
        right_btn.setBackgroundResource(R.drawable.tag_button_tag);
    }

    @Override
    public void doInitData() {
        mTagAblumAdapter = new TagAblumAdapter(mContext, mDatalist);
        gv_album.setAdapter(mTagAblumAdapter);
        doGetData();
    }

    void initData() {
        mDatalist.clear();
        TagAlbumItem item = new TagAlbumItem();
        item.Type = TagAlbumItem.DataType.ADD_TAG;
        mDatalist.add(item);
    }

    void refreshData() {
        nextPage = "1";
        mIsLastPage = false;
        doGetData();
    }

    void doGetData() {
        if (mIsLastPage || mIsRefreshing) {
            gv_album.onRefreshComplete();
            return;
        }
        Loger.d("next page:" + nextPage);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("page", nextPage);
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_TAG_ALBUM_LIST, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {

                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;
    }

    /**
     * 解析返回的标签相册列表数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            if (nextPage.equals("1")) {
                initData();
            }
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    addDataItem(o);
                }
            }
            if (mDatalist.size() > 1) {
                list_empty_view.setVisibility(View.INVISIBLE);
                gv_album.setVisibility(View.VISIBLE);
            } else {
                list_empty_view.setVisibility(View.VISIBLE);
                gv_album.setVisibility(View.GONE);
            }
            mTagAblumAdapter.notifyDataSetChanged();
        }
        nextPage = data.optString("nextPage");
        gv_album.onRefreshComplete();
        mIsRefreshing = false;
        if (nextPage.equals("-1")) {
            mIsLastPage = true;
        }
    }

    /**
     * 添加新的数据源
     *
     * @param o
     */
    private void addDataItem(JSONObject o) {
        String tag = o.optString("tag");
        String tagPhotos = o.optString("tagPhotos");
        String photo = o.optString("photo");
        String tag_id = o.optString("tag_id");
        JSONArray photoList = o.optJSONArray("photoList");
        String[] urls = new String[0];
        if (photoList != null && photoList.length() > 0) {
            urls = new String[photoList.length()];
            for (int j = 0; j < urls.length; j++) {
                urls[j] = photoList.optString(j);
            }
        }
        TagAlbumItem item = new TagAlbumItem();
        item.album_name = tag;
        item.count = tagPhotos;
        item.cover_url = photo;
        item.tag_id = tag_id;
        item.cover_urls = urls;
        item.Type = TagAlbumItem.DataType.NORMAL;
        mDatalist.add(mDatalist.size() - 1, item);
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_BATCH_ADD_TAG_PHOTO:
            case PuTaoConstants.EVENTBUS_BATCH_REMOVE_TAG_PHOTO:
                Bundle bundle = event.bundle;
                if (bundle != null) {
                    String tag = bundle.getString("tag_name");
                    //TODO:1代表移除0代表新增
                    int type = bundle.getInt("type", 1);
                    int count = bundle.getInt("count", 0);
                    String cover = bundle.getString("cover", "");
                    updateTagAlbumPhotoCounts(tag, type, count, cover);
                }
                break;
            case PuTaoConstants.EVENTBUS_DELETE_OR_ADD_TAG_SUCCESS:
                refreshData();
                break;
        }
    }


    /**
     * 更新标签相册的照片数量
     *
     * @param tag
     * @param type
     * @param count
     */
    void updateTagAlbumPhotoCounts(String tag, int type, int count, String cover) {
        for (int i = 0; i < mDatalist.size(); i++) {
            if (mDatalist.get(i).album_name.equals(tag)) {
                int a_count = Integer.valueOf(mDatalist.get(i).count);
                if (type == 0) {
                    a_count += count;
                } else {
                    a_count -= count;
                }
                mDatalist.get(i).cover_url = cover;
                mDatalist.get(i).count = a_count + "";
                break;
            }
        }
        mTagAblumAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.right_btn:
                ActivityHelper.startActivity(mActivity, ActivityTagManager.class);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
